package sparkStream

import org.apache.kafka.clients.producer.{KafkaProducer, ProducerConfig, ProducerRecord}
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.SparkConf
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark.streaming.kafka010.KafkaUtils
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent

import java.util.HashMap
import scala.collection.mutable

object Kafka {
  def main(args: Array[String]): Unit = {

    val conf = new SparkConf().setMaster("local[*]").setAppName("hi0")

    val ssc = new StreamingContext(conf, Seconds(2))
     ssc.sparkContext.setLogLevel("error")
    val kafkaParams = Map[String, Object](
      "bootstrap.servers" -> "123.56.187.176:9092",
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> "niit030303",
      "enable.auto.commit" -> (false: java.lang.Boolean)
    )

    val topicname = Array("stuInfo")
    val streamRdd = KafkaUtils.createDirectStream[String, String](
      ssc,
      PreferConsistent,
      Subscribe[String, String](topicname, kafkaParams)
    )


    //  producer 配置项
    val property = new HashMap[String,Object]()
    property.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.244.11:9092")
    property.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer")
    property.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer")



    val res=streamRdd.map(_.value())
    val result=res.flatMap(_.split(" ")).map((_,1)).reduceByKeyAndWindow(_+_,Seconds(4),Seconds(4))
    result.foreachRDD(
      x=>{
        println("-------数据是-------")
        x.foreach(
         obj=>{
           println(obj)
           val producer=new KafkaProducer[String,String](property)
           producer.send(new ProducerRecord[String,String]("lol",obj.toString()))
           producer.close()
         }

         )
      }

    )



    ssc.start()
    ssc.awaitTermination()//kafka数据

    //将数据发送到kafka的topic当中，发送到topic lol

  }

}
